import logging

import requests

logger = logging.getLogger(__name__)

class WalkingRouteService:
    def __init__(self, api_key):
        self.base_url = "https://api.map.baidu.com/directionlite/v1/walking"
        self.api_key = api_key
        self.logger = logger

    def validate_coordinate(self, coord):
        try:
            lat_str, lng_str = coord.split(',')
            if len(lat_str.split('.')[1]) > 6 or len(lng_str.split('.')[1]) > 6:
                raise ValueError("小数点精度超过6位")
            
            lat = float(lat_str)
            lng = float(lng_str)
            return -90 <= lat <= 90 and -180 <= lng <= 180
        except (ValueError, AttributeError, IndexError) as e:
            self.logger.error(f"坐标验证失败: {coord} | 错误: {str(e)}")
            return False

    def get_walking_route(self, origin, destination, **kwargs):
        if not all(self.validate_coordinate(c) for c in [origin, destination]):
            raise ValueError("坐标格式应为'纬度,经度'且小数精度不超过6位")

        params = {
            'origin': f'{origin.split(",")[1]},{origin.split(",")[0]}',
            'destination': f'{destination.split(",")[1]},{destination.split(",")[0]}',
            'ak': self.api_key,
            **kwargs
        }

        try:
            response = requests.get(self.base_url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()

            if data.get('status') != 0:
                error_msg = data.get('message', '未知错误')
                self.logger.error(f"百度API错误: {error_msg}")
                return None

            return self._parse_api_response(data)
        except requests.exceptions.RequestException as e:
            self.logger.error(f"请求异常: {str(e)}")
            return None
        except (KeyError, IndexError) as e:
            self.logger.error(f"响应解析异常: {str(e)}")
            return None

    def _parse_api_response(self, data):
        try:
            result = data['result']['routes'][0]
            return {
                'distance': result['distance'],
                'duration': result['duration'],
                'steps': [
                    {
                        'instruction': step['instruction'],
                        'distance': step['distance'],
                        'duration': step['duration'],
                        'path': step['path']
                    } for step in result['steps']
                ]
            }
        except KeyError as e:
            self.logger.error(f"缺少必要响应字段: {str(e)}")
            return None

# 使用示例
if __name__ == "__main__":
    service = WalkingRouteService(api_key="47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr")
    result = service.get_walking_route(
        origin="20.011160,110.339303",
        destination="19.936404,110.452562"
    )
    print(result)